var inervalId; //接收进度条时间
var initialopen=1; //初始化  表示第一次打开页面  第一次打开页面时 window窗口还没加载完毕，onSelect()事件直接调用 窗口会报错
var menuId='门卫管理访单';

$(function () {
    $('#FHwin').window({
        width: 400,
        height: 350,
        modal:true,collapsible:false,minimizable:false,maximizable:false,
        draggable:false,
        resizable:false,
        closed:true,
        noheader: true,
        closable:false
    });

    $('#visitorCategory').combobox({
        data:[{name:'供应商'},{name:'物流'},{name:'客户'},{name:'政府机关'},{name:'个人'},{name:'其他'}],
        valueField:'name',
        textField:'name',
        limitToList:true
    });
    $('#type').combobox({
        data:[{id:10,name:'普通访客'},{id:11,name:'贵宾访客'}],
        valueField:'id',
        textField:'name',
        limitToList:true,
        required:true
    });



    //全局 添加自定义请求头
    $.ajaxSetup({
        headers: {"usersid":Strusersid}
    });

    initKendoUiGrid()

    // let intervalId = setInterval(function() {
    //     seteslfocus(); //指定焦点位置
    // }, 2000); // 每隔2000毫秒执行这个函数

    // clearInterval(intervalId);

    // let intervalGrid = setInterval(function() {
    //     btn_refresh(); //
    // }, 60000); // 每隔2000毫秒执行这个函数

    btn_refresh();


    //绑定扫码事件
    // var input = document.getElementById('esl');
    // input.addEventListener('input', function(event) {
    //     var value = event.target.value;
    //     if (value.length>0){
    //         ScanCode(value);
    //         input.value = '';
    //     }
    // });

});

//打开模态窗 修改
function openwin() {
    var kGrid = $("#bill").data("kendoGrid");
    var row = kGrid.select();
    var dataItem = kGrid.dataItem(row);
    if (dataItem){
        $("#form").form('load', dataItem);
        $('#FHwin').window('open');
    }
}

function updateclientdetail() {
    $.messager.defaults = {ok: "确定", cancel: "取消", width: 300, closable: false};
    $.messager.confirm('确认', '是否确定修改访客信息？', function (r) {
        if (r) {
            let Obj={
                id:$("#id").textbox('getValue'),
                realName:$("#realName").textbox('getValue'),
                company:$("#company").textbox('getValue'),
                phone:$("#phone").textbox('getValue'),
                idNumber:$("#idNumber").textbox('getValue'),
                visitorCategory:$("#visitorCategory").combobox('getValue'),
                type:$("#type").combobox('getValue'),
            };
            updateclientSQL(Obj);
        }
    });

}

function setaudit(val) {
    $.messager.defaults = {ok: "确定", cancel: "取消", width: 300, closable: false};
    $.messager.confirm('确认', val==1?'是否确定恢复访客信息？':'是否确定停用访客信息？', function (r) {
        if (r) {
            var kGrid = $("#bill").data("kendoGrid");
            var row = kGrid.select();
            var dataItem = kGrid.dataItem(row);
            if (dataItem){
                let Obj={
                    id:dataItem.id,
                    state:val
                };
                updateclientSQL(Obj);
            }else{
                $.messager.alert('提示','未选择对应数据');
            }
        }
    });

}

//修改访客资料
function updateclientSQL(row) {
    // $.messager.progress();
    $.ajax({
        url:'https://showawx.xdfznh.club/visitorbe/userWeixin/update',
        type: 'POST',
        dataType: 'json',
        // data:value,
        data:JSON.stringify(row),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            // let data=cdata.data;
            console.log(cdata);
            if (cdata.success){
                $('#FHwin').window('close')
                btn_refresh();
            }else{
                $.messager.alert('提示',cdata.msg);
                return;
            }

        },
        complete: function (XMLHttpRequest, textStatus) {
            // $.messager.progress('close');
        }
    });
}


//设置接收扫码数据的文本 焦点
function seteslfocus() {
    document.getElementById('esl').focus();
}

//查询
function btn_refresh() {
    btn_refresh_zc();
    // switch (getSelectedIndex()) {
    //     case 0:
    //         btn_refresh_zc();
    //         break;
    //     case 1:
    //         // btn_refresh_zf();
    //         break;
    // }
}


function btn_refresh_zc() {
    var kGrid = $("#bill").data("kendoGrid");
    $.ajax({
        // headers: {"usersid":Strusersid},
        // url: strLin + "customSqlAccount/callProc",
        url:'https://showawx.xdfznh.club/visitorbe/userWeixin/getAllVisitor',
        type: 'POST',
        dataType: 'json',
        // data: JSON.stringify(['usp_getquality_sum04',YMD,linezl]),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            let data=cdata.data;
            console.log(data);
            data.forEach(item => {
                if (isNull(item.createTime,0) != 0){item.createTime = new Date(item.createTime);}
            });
            kGrid.dataSource.data(data);
        },
        complete: function (XMLHttpRequest, textStatus) {

        }
    });
}

/**
 * 将数组去重
 * @param arr
 * @param attribute
 * @returns {[]}
 */
function unique(arr, attribute) {
    let new_arr = [];
    let json_arr = [];
    for (let i = 0; i < arr.length; i++) {
        if (new_arr.indexOf(arr[i][attribute]) == -1) {
            new_arr.push(arr[i][attribute]);
            json_arr.push(arr[i]);
        }
    }
    return json_arr;
}


// 全部 构建表结构
function initKendoUiGrid() {
    var SUFFIX='_01';
    /*不做过滤，这块代码删除掉了*/
    var realName = new kendo.data.DataSource({data: []});
    var company = new kendo.data.DataSource({data: []});
    var phone = new kendo.data.DataSource({data: []});
    var idNumber = new kendo.data.DataSource({data: []});
    var visitorCategory = new kendo.data.DataSource({data: []});
    var userType = new kendo.data.DataSource({data: []});
    var invalid = new kendo.data.DataSource({data: []});
    var dataSource = new kendo.data.DataSource({
        pageSize: 200,
        schema: {
            model: {
                fields: {
                    // duration_hour: {type: "number"},
                    createTime: {type: "date"}
                }
            }
        },
        aggregate: [
            // {field: "duration_hour", aggregate: "sum"},
        ],
        change: function (e) {
            //获取过滤条件
            let filtrer = this.filter();
            //获取所有数据
            let allData = this.data();
            //进行过滤条件的筛选
            let query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            // let data = query.filter(filtrer).data;
            let data = allData;
            realName.data(unique(data, 'realName'));
            company.data(unique(data, 'company'));
            phone.data(unique(data, 'phone'));
            idNumber.data(unique(data, 'idNumber'));
            visitorCategory.data(unique(data, 'visitorCategory'));
            userType.data(unique(data, 'userType'));
            invalid.data(unique(data, 'invalid'));

        },
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text == '查询' || (btn.linkbutton('options').text == '过滤')) {
                    btn.linkbutton('disable')
                }
            })
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text == '查询' || (btn.linkbutton('options').text == '过滤')) {
                    btn.linkbutton('enable')
                }
            })
        }
    });

    let columns=[
        {
            field: "", title: "序号",template: "<span class='row_number'></span>", width: 40
        },
        {field: 'id', title: '主表主键', hidden: true, width: 80,},
        {
            field: 'realName', title: '姓名', width: 80,
            filterable: {multi: true, search: true, dataSource: realName},
            attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
        },
        {
            field: 'company', title: '公司', width: 80,
            filterable: {multi: true, search: true, dataSource: company},
            attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
        },
        {
            field: 'phone', title: '电话', width: 80,
            filterable: {multi: true, search: true, dataSource: phone},
            attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
        },
        {
            field: 'idNumber', title: '身份证号', width: 80,
            filterable: {multi: true, search: true, dataSource: idNumber},
            attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
        },
        {
            field: 'visitorCategory', title: '类别', width: 80,
            filterable: {multi: true, search: true, dataSource: visitorCategory},
            attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
        },
        {
            field: 'userType', title: '类型', width: 80,
            filterable: {multi: true, search: true, dataSource: userType},
            attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
        },
        {
            field: 'createTime', title: '注册时间', width: 80,
            format: "{0:yyyy-MM-dd}",
            filterable: {
                ui: function(element) {
                    element.kendoDatePicker({
                        format: "yyyy-MM-dd"
                    });
                }
            },
            attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
        },
        {
            field: 'invalid', title: '停用', width: 80,
            filterable: {multi: true, search: true, dataSource: invalid},
            attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
        },
        {
            field: '',
            title: '',
            width: 100,
            attributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
        },

    ];
    var grid = $("#bill").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: true,
        persistSelection: true,
        allowCopy: true,
        title: "报表",
        // columnMenu: {
        //     sortable: true
        // },
        excel: {
            fileName: "访客资料.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        pageable: {
            pageSize: 200
        },
        dataSource: dataSource,
        columns: columns,
        reorderable: true,
        height: '99%',
        dataBound: function () {  //dataBound 事件在网格数据绑定完成后触发。您可以使用该事件来执行与数据绑定后相关的操作，例如修改数据、设置样式、执行计算等
            var rows = this.items();
            $(rows).each(function () {
                var index = $(this).index() + 1;
                var rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });
            var kgrid = $("#bill").data("kendoGrid");    // 行样式
            let trs = kgrid.tbody.find("tr");
            trs.each(function (i, row) {
                let data = kgrid.dataItem(row);
                let invalid = data['invalid'];

                // if (state == 0) $(row).css({"color": "red", "text-decoration": "line-through"});
                if (invalid !=='') $(row).css({"color": "red"});
                // if (audit_department === 2 || audit_factory === 2 || audit_personnel === 2 || audit_manager === 2 ) $(row).css({"color": "#0000FF"});
            });
        },
    });

    var grid01 = $('#bill').data('kendoGrid');
    let columnNames = [];
    columns.forEach(item => {
        if (item['field']) {
            columnNames.push(item['field']);
        }
    });
    loadOptions(grid01, columnNames, columns, SUFFIX);
    //双击事件
    grid.on('dblclick', 'tr', function () {
        //  代码
        var kGrid = $("#bill").data("kendoGrid");
        var row = kGrid.select();
        var dataItem = kGrid.dataItem(row);
        var id = dataItem['id'];

        // console.log(dataItem)
        $("#form").form('load', dataItem);
        $('#FHwin').window('open');

    });
    //右击事件
    grid.on('contextmenu', 'tr', function (e) {
        // e.preventDefault();
        // //  代码
        // var menu = '<div id="menu">'
        //     + '<div data-options="iconCls:\'icon-ok\'">审核通过</div>'
        //     + '<div data-options="iconCls:\'icon-undo\'">审核驳回</div>'
        //     + '<div data-options="iconCls:\'icon-clear\'">审核取消</div>'
        //     + '<div data-options="iconCls:\'icon-no\'">审核作废</div>'
        //     + '</div>';
        // if ($('#menu').length <= 0) {
        //     $('body').append(menu);
        // }
        // $('#menu').menu({
        //     onClick: function (item) {
        //         switch (item.text) {
        //             case '审核驳回':
        //                 // setaudit(2);
        //                 $('#B').window('open');
        //                 //光标定位
        //                 $('#B_remark').textbox().next('span').find('input').focus();
        //                 break;
        //             case '审核作废':
        //                 setstate_zf(0);
        //                 break;
        //             case '审核通过':
        //                 setaudit(1);
        //                 break;
        //             case '审核取消':
        //                 setaudit(0);
        //                 break;
        //
        //         }
        //     }
        // });
        // $('#menu').menu('show', {
        //     left: e.pageX,
        //     top: e.pageY
        // });
    });
    //  单击事件
    grid.on('click', 'tr', function () {
        //  代码
        // setStatusA('0-1')
        // $('#bt_ll').linkbutton('enable');
        // $('#bt_ll01').linkbutton('enable');

    });
}

//列隐藏显示模态窗
function btn_open_column_list() {
    let kGrid =$('#bill01').data('kendoGrid'); // getSelectedGrid();
    let options = kGrid.getOptions().columns;
    if ($('#btn_open_column_list').length <= 0) {
        let div = $(`<div data-options="
                    resizable:true,iconCls:'icon-filter',width:200,height:400,modal:true,title:'列',
                    onClose:function(){$(this).dialog('destroy')}" 
                          class="easyui-dialog" id="btn_open_column_list">
                   </div>`);
        let form = $('<form style="width: 100%;height: 100%;"></form>')
        for (let i of options) {
            if (i.field) {
                let checkbox = $(`<div style="width: 100%;height: auto;padding: 5px;">
                <input class="easyui-checkbox" name="${i.field}" data-options="label:'${i.title}',
                labelWidth:120,value:true,name:'${i.field}'">
                </div>`);
                form.append(checkbox);
            }
        }
        let container = $(`<div></div>`);
        form.appendTo(div);
        div.appendTo(container);
        $('body').append(container);
        $.parser.parse($('#btn_open_column_list').parent());
        let formData = {};
        options.map(item => {
            formData[item['field']] = item['hidden'] == undefined ? true : !item['hidden'];
        })
        $('#btn_open_column_list form').eq(0).form('load', formData);
        $('#btn_open_column_list form .easyui-checkbox').each(function () {
            //  绑定事件
            $(this).checkbox({
                onChange: function (checked) {
                    let opts = $(this).checkbox('options');
                    if (checked) {
                        kGrid.showColumn(opts.name);
                    } else {
                        kGrid.hideColumn(opts.name);
                    }
                }
            })
        })
    } else {
        $('#btn_open_column_list').dialog('open');
    }
}

//  清除过滤
function btn_cancel_filter() {
    let kGrid0 = $("#bill01").data("kendoGrid");
    // let kGrid0 =getSelectedGrid()
    if (kGrid0 != undefined) {
        kGrid0.dataSource.filter({});
    }
}


//导出
function btn_export() {
    // if (!determineQX(menuId,'pexport')){$.messager.alert('提示', '当前登录账号无权限！');return;}
    $("#bill").data("kendoGrid").saveAsExcel();

    // switch (getSelectedIndex()) {
    //     case 0:
    //         $("#bill").data("kendoGrid").saveAsExcel();
    //         break;
    //     case 1:
    //         $("#bill_zf").data("kendoGrid").saveAsExcel();
    //         break;
    // }
}

function getSelectedIndex() {
    let tab = $('#tabs').tabs('getSelected');
    let index = $('#tabs').tabs('getTabIndex', tab);
    return index;
}

/****************************************************************************************** */

//关闭当前标签页事件
function closeTab() {
    window.parent.closeTab();
}